﻿using AutoMapper;
using MediatR;
using PublicClass;
using PublicClass.BreedingEnum;
using S.Breeding.Domain;
using S.Breeding.Infrastructure;
using S.Breeding.Read.Api.Application.Command.DeathManageCommand;

namespace S.Breeding.Read.Api.Application.CommandHandlers.DeathManageCommandHandlers
{
    public class DeathManageListCommandHandlers : IRequestHandler<DeathManageListCommand, PageInfo<DeathManage>>
    {
        private readonly IRepository<DeathManage> repository;
        private readonly PageInfo<DeathManage> pageInfo;
        private readonly IMapper mapper;
        public DeathManageListCommandHandlers(IRepository<DeathManage> repository, IMapper mapper, PageInfo<DeathManage> pageInfo)
        {
            this.repository = repository;
            this.mapper = mapper;
            this.pageInfo = pageInfo;
        }

        public async Task<PageInfo<DeathManage>> Handle(DeathManageListCommand request, CancellationToken cancellationToken)
        {
                var list = repository.All().Result;
                if (!string.IsNullOrEmpty(request.Earbugles))
                {
                    list = list.Where(x => x.Earbugles == request.Earbugles);
                }
                if (request.Sdate != null)
                {
                    list = list.Where(x => x.DeathTime >= request.Sdate);
                }
                if (request.Edate != null)
                {
                    list = list.Where(x => x.DeathTime <= request.Edate);
                }
                if (request.DeathCause > 0)
                {
                    list = list.Where(x => x.DeathCause == request.DeathCause);
                }
                pageInfo.totalCount = list.Count();
                pageInfo.pageCount = (int)Math.Ceiling(pageInfo.totalCount * 1.0 / request.pageSize);
                list = list.OrderByDescending(x => x.DeathTime).Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize);
                return new PageInfo<DeathManage>
                {
                    datas = list.ToList(),
                    totalCount = pageInfo.totalCount,
                    pageCount = pageInfo.pageCount,
                };
        }
    }
}
